/*
 * @Title: 登录相关store
 * @Description: 描述
 * @FilePath: /vue3-admin-naive-starter/src/stores/login.ts
 */

import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { RemovableRef } from '@vueuse/core'
import { useLoginApi, type LoginForm } from '@/api/login'
import { encrypt } from '@/utils/AESPassword'

export const useLoginStore = defineStore('login', () => {
  /**
   * 用户token
   */
  const token: RemovableRef<string> = useStorage('token', '')
  /**
   * 更新token
   */
  const updateToken = (newToken: string) => {
    token.value = newToken
  }
  /**
   * 登录操作
   */
  const loginAction = async (form: LoginForm) => {
    const { pwd } = form
    const md5Pwd = encrypt(pwd)
    try {
      const res = await useLoginApi.login({
        ...form,
        pwd: md5Pwd
      })
      const { data } = res
      updateToken(data)
      // 登录过后获取用户菜单原始数据和权限数据 -->登陆后刷新页面去调用
      // const { getUserInfo } = useUserStore()
      // await getUserInfo()
      return true
    } catch (error) {
      /**Empty */
      return Promise.reject(error)
    }
  }
  return {
    token,
    updateToken,
    loginAction
  }
})
